import { request } from '../../request/index';
import regeneratorRuntime from '../../lib/runtime/runtime';

Page({
  data: {
    tabs: [
      {
        id: 0,
        value: '全部',
        isActive: true
      },
      {
        id: 1,
        value: '待付款',
        isActive: false
      },
      {
        id: 2,
        value: '待发货',
        isActive: false
      },
      {
        id: 3,
        value: '退款/退货',
        isActive: false
      }
    ],
    orderList: []
  },
  onShow(options) {
    // onShow不同于onLoad无法在形参上接收options参数，获取url上的type
    // 1.获取当前的小程序的页面栈-数组，长度最大是10
    let pages = getCurrentPages();
    // 2.数组中索引最大的页面就是当前页面
    let currentPage = pages[pages.length - 1];
    const {type} = currentPage.options;
    // 激活选中页面标题
    this.changeTitleByIndex(type - 1);
    this.getOrderList(type);
  },
  handleItemChange(e) {
    // 获取被点击的标题索引
    const {index} = e.detail;
    this.changeTitleByIndex(index);
    // 重新发送请求
    this.getOrderList(index + 1);
  },
  // 点击标题激活选中
  changeTitleByIndex(index) {
    // 修改源数组
    let {tabs} = this.data;
    tabs.forEach((v,i) => {
      i === index ? v.isActive = true : v.isActive = false
    });
    // 赋值到data中
    this.setData({
      tabs
    })
  },
  async getOrderList(type) {
    const token = wx.getStorageSync("token");
    if(!token) {
      wx.navigateTo({
        url: '/pages/auth/auth'
      });
      return;
    }
    const header = { Authorization: token };
    const res = await request({
      url: '/my/orders/all',
      data: {type},
      header
    })
    // console.log(res);
    this.setData({
      orderList: res.orders.map(v => ({
        ...v,
        create_time_cn:(new Date(v.create_time * 1000).toLocaleString())
      }))
    })
  }
})